<template>
  <div class="wrapper">
    <div id="container" class="map-container">
    </div>
    <a-modal v-model="trackVisible" width="69.9%" :title="trackTitle" :footer="null">
      <EBikeMapTrack :carCode="trackCarCode" :location="trackLocation"></EBikeMapTrack>
    </a-modal>
  </div>
</template>

<i18n>
  {
    "zh-CN": {
      "trajectoryDetails":"轨迹详情"
    },
    "en-US": {
      "trajectoryDetails":"Trajectory details"
    },
    "fr-FR": {
      "trajectoryDetails":"Détails de la piste"
    }
  }
</i18n>

<script>
function isScriptAlreadyLoaded(srcCheck) {
  var scripts = document.getElementsByTagName('script');
  for (var i = 0; i < scripts.length; i++) {
      if (scripts[i].src.includes(srcCheck)) {
          return true;
      }
  }
  return false;
}

import { wgs84togcj02 } from 'gps-convert'
import { httpAction, getAction } from '@/api/manage'
import EBikeMapTrack from './components/EBikeMapTrack'
export default {
  components: {
    EBikeMapTrack
  },
  data(){
    return{
      map: null,
      ebikeList: [],
      trackVisible: false,
      trackTitle: '',
      trackCarCode: '',
      trackLocation: {},
      url:{
        ebikeList: "/rental/ebike/location-list",
      }
    }
  },
  created(){
    this.showMap();
  },
  methods:{
    async loadScript() {
      const KEY = window._CONFIG['gMapKey'];
      const scriptSrc = `https://maps.googleapis.com/maps/api/js?libraries=geometry&key=${KEY}`;
      return new Promise((resolve, reject) => {
        if (isScriptAlreadyLoaded(scriptSrc)) {
          console.log('The script has already been loaded.');
          resolve(); 
        } else {
          const script = document.createElement("script");
          script.type = "text/javascript";
          script.src = scriptSrc;
          script.onload = () => {
            console.log('Script loaded successfully.', scriptSrc);
            resolve();
          };
          script.onerror = (error) => {
            console.error('Error loading script:', error);
            reject(error); 
          };
          document.body.appendChild(script);
        }
      });
    },
    async showMap(){
      await this.loadScript();
      if(!this.map){
          await this.initMap();
      }
      await this.getEBikeList();
    },
    async initMap(){
      this.map = new google.maps.Map(document.getElementById('container'), {
          zoom: 12, // 设置地图缩放级别
      });
    },
    async getEBikeList() {
      const res = await getAction(this.url.ebikeList);
      if (res.success) {
        this.ebikeList = res.result;
        var bounds = new google.maps.LatLngBounds();
        for (let i = 0; i < this.ebikeList.length; i++) {
          const item = this.ebikeList[i];
          this.addEbikeMarker(item, bounds);
        }
        this.map.fitBounds(bounds);
      }
    },
    markerTemplate(status){
      let markerIcon;
      if(status){
        markerIcon = `/vehicle${status}.png`;
      }else{
        markerIcon = `/vehicle1.png`;
      }
      return markerIcon;
    },
    addEbikeMarker(ebike, bounds){
      const lngLat = wgs84togcj02([ebike.longitude, ebike.latitude])
      const position = { lat: lngLat[1], lng: lngLat[0] };
      const customIcon = this.markerTemplate(ebike.status);
      const MarkerWithLabel = require('markerwithlabel')(google.maps);
      let marker = new MarkerWithLabel({
        position: position,
        map: this.map,
        icon: {
          url: customIcon, // 自定义图标URL
          scaledSize: new google.maps.Size(50, 50) // 设置图标大小（宽度和高度）
        },
        labelContent: ebike.carCode,
        labelAnchor: new google.maps.Point(50, 70), // 设置标签锚点
        labelStyle: {
          opacity: 0.75,
          padding: "5px 10px",
          textAlign: "center",
          color: "red",
          fontWeight: "bold",
          fontSize: "12px",
          width: "100px",
        }
      });
      google.maps.event.addListener(marker, 'click', () => {
        console.log("click marker:-----------:", ebike);
        this.trackVisible = true;
        this.trackCarCode = ebike.carCode;
        this.trackTitle = `${ebike.carCode} ${this.$t('trajectoryDetails')}`;
        this.trackLocation = {
          latitude: ebike.latitude,
          longitude: ebike.longitude,
        };
      });
      bounds.extend(marker.position);
    }
  }
}
</script>

<style lang="less" scoped>
.wrapper{
  width: 100%;
  height: calc(100vh - 94px);
  padding: 0;
  margin: 0;
  position: relative;
  
  .map-container {
    width: 100%;
    height: 100%;
  }
}
</style>